﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PACKETPARSERMAX20.CORE;

namespace PACKETPARSERMAX20.CONSOLE
{
    public static class DefinitionGen
    {


        public static void Process()
        {
            string source = @".\..\PACKETPARSERMAX20.Core\DEFINITIONS\_MAIN\";

            SortedList<string, int> opcodes = new SortedList<string, int>();

            for (int i = 1; i <= (int)PACKETPARSERMAX20.CORE.Opcodes.NUM_MSG_TYPES; i++)
            {
                string name = ((PACKETPARSERMAX20.CORE.Opcodes)i).ToString();

                if (!name.IsNumeric() && name.IndexOf("UNKNOWN") == -1 && name.IndexOf("OBSOLETE") == -1 && name.IndexOf("MSG_NULL_ACTION") == -1 && name.IndexOf("NUM_MSG_TYPES") == -1 && name.IndexOf("UMSG_") == -1)
                    opcodes.Add(name.Trim(), i);
            }

            string[] currentdefs = System.IO.Directory.GetFiles(source, "*.cs", System.IO.SearchOption.AllDirectories);

            SortedList<string, string> defList = new SortedList<string, string>();
            foreach (string currentdef in currentdefs)
            {
                string name = System.IO.Path.GetFileNameWithoutExtension(currentdef);
                if (name.StartsWith("CMSG_") || name.StartsWith("MSG_") || name.StartsWith("SMSG_"))
                    defList.Add(System.IO.Path.GetFileNameWithoutExtension(currentdef).Replace("_DEF", ""), currentdef);
            }

            string[] dirs = System.IO.Directory.GetDirectories(source);


            foreach (string def in defList.Keys)
            {
                if (!opcodes.ContainsKey(def))
                {
                    string file = defList[def];

                    Console.WriteLine("NO IN LATEST BUILD: " + file);
                }
            }

            string template = System.IO.File.ReadAllText(".\\Template.txt");

            foreach (string opcode in opcodes.Keys)
            {
                if (!defList.ContainsKey(opcode))
                {

                    Console.WriteLine("NEW OPCODE: " + opcode);

                    string newdefname = opcode + "_DEF";
                    string category = opcode.Substring(0, opcode.IndexOf("_"));

                    string data = template.Replace("Template", opcode  );
                    data = data.Replace("[CREATED]", DateTime.Now.ToString());
                    data = data.Replace("[BUILD]", "3.3.5.12340");
                    data = data.Replace("[OPCODE]", opcodes[opcode].ToString());

                    string newfile = source + category + "\\_SORT\\" + newdefname + ".cs";
                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(newfile))
                    {
                        sw.Write(data);
                        sw.Close();
                    }
                }
            }

        }
    }
}
